﻿Imports MySoft.Map.Data
Imports System.Text

Partial Public Class TransferPage
    Inherits Mysoft.Map.Application.Security.AppPage

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strProjGUID As String = String.Empty
        Dim strUserGUID As String = String.Empty
        Dim strUrl As String = String.Empty
        Dim strSysSite As String = String.Empty
        Dim blnIsERP As Boolean = False
        If Not String.IsNullOrEmpty(Request.QueryString("url")) Then
            strUrl = Request.QueryString("url").ToString()
            strUserGUID = Session("UserGUID").ToString()

            If String.IsNullOrEmpty(Request.QueryString("ProjGUID")) Then
                lb_Msg.Text = "未获取到项目[Guid]参数！"
                Return
            End If

            If String.IsNullOrEmpty(Request.QueryString("SysSite")) Then
                lb_Msg.Text = "未获取到业务子系统[SysSite]参数！"
                Return
            End If

            '供ERP内部调用使用
            If Not String.IsNullOrEmpty(Request.QueryString("isERP")) AndAlso Request.QueryString("isERP") = "1" Then
                blnIsERP = True
            End If

            strSysSite = Request.QueryString("SysSite").ToString()
            strProjGUID = Request.QueryString("ProjGUID").ToString()

            '各子系统对象类型不同，需要进行校验.
            Dim strApplication As String
            Dim strObjTypeList As String()
            Select Case strSysSite.ToUpper()
                Case "MysoftERP_成本系统".ToUpper()
                    strApplication = "0201"
                    strObjTypeList = New String() {"ProjectGUID_POM_CBGL", "ProjectGUID_POM_DCPDB", "ProjectGUID_POM_HTGL", "ProjectGUID_POM_CBGL_Budget"}
                    Exit Select
                Case "MysoftERP_计划系统".ToUpper()
                    strApplication = "0202"
                    strObjTypeList = New String() {"ProjectGUID_POM_XMJD"}
                    Exit Select
                Case "MysoftERP_售楼系统".ToUpper()
                    strApplication = "0101"
                    strObjTypeList = New String() {"ProjGUID"}
                    Exit Select
                Case Else
                    lb_Msg.Text = "业务子系统[SysSite]参数错误！"
                    Return
            End Select
            '进行项目定位处理
            If LocationProjectAndUnit(strUserGUID, strProjGUID, strObjTypeList, strApplication, blnIsERP) Then
                If strUrl.IndexOf("?") < 0 Then
                    strUrl &= "?_=" & New System.Random().NextDouble().ToString()
                End If
                Response.Redirect(strUrl & "&SysSite=" & Server.UrlEncode(strSysSite) + "&ProjGUID=" + Server.UrlEncode(strProjGUID))
            Else
                lb_Msg.Text = "项目定位失败！"
                Return
            End If
        Else
            lb_Msg.Text = "未获取到[URL]参数！"
            Return
        End If

    End Sub

    ''' <summary>
    ''' 转换用户默认项目及当前公司
    ''' </summary>
    ''' <param name="strUserGUID">用户GUID</param>
    ''' <param name="strProjGUID">项目GUID</param>
    ''' <returns>True or False</returns>
    ''' <remarks></remarks>
    Private Function LocationProjectAndUnit(ByVal strUserGUID As String, ByRef strProjGUID As String, ByVal arrObjType As String(), ByVal strApplication As String, ByVal blnIsERP As Boolean) As Boolean
        Dim strSQL As String = String.Empty
        Dim dt As DataTable = Nothing
        If blnIsERP Then
            strSQL = String.Format(" SELECT TOP 1 p_Project.ProjGUID,myBusinessUnit.BUGUID ,myBusinessUnit.BUNAME,myBusinessUnit.IsEndCompany FROM myBusinessUnit" & _
                 " INNER JOIN p_Project ON myBusinessUnit.BUGUID = p_Project.BUGUID AND ApplySys LIKE	'%{0}%' " & _
                 " WHERE p_Project.ProjGUID='{1}' Order by p_Project.ProjCode", strApplication, strProjGUID)
        Else
            strSQL = String.Format(" SELECT TOP 1 p_Project.ProjGUID,myBusinessUnit.BUGUID ,myBusinessUnit.BUNAME,myBusinessUnit.IsEndCompany FROM myBusinessUnit" & _
                 " INNER JOIN p_Project ON myBusinessUnit.BUGUID = p_Project.BUGUID AND ApplySys LIKE	'%{0}%' " & _
                 " WHERE p_Project.MainProjGUID='{1}' Order by p_Project.ProjCode", strApplication, strProjGUID)
        End If

        dt = MyDB.GetDataTable(strSQL)

        If dt.Rows.Count > 0 Then
            Dim row As DataRow = dt.Rows(0)
            strProjGUID = row.Item("ProjGUID").ToString()
            If SetDefaultProject(strUserGUID, strProjGUID, arrObjType) AndAlso SetDefaultUnit(row.Item("BUGUID").ToString(), row.Item("BUNAME").ToString(), row.Item("IsEndCompany").ToString()) Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function

    ''' <summary>
    ''' 设置用户默认项目
    ''' </summary>
    ''' <param name="strUserGUID">用户GUID</param>
    ''' <param name="strProjGUID">项目GUID</param>
    ''' <returns>True or False</returns>
    ''' <remarks></remarks>
    Private Function SetDefaultProject(ByVal strUserGUID As String, ByVal strProjGUID As String, ByVal arrObjType As String()) As Boolean
        Dim sbSQL As New StringBuilder
        For Each strType As String In arrObjType
            sbSQL.AppendFormat(" IF EXISTS(SELECT * FROM myCurrArgs WHERE UserGUID ='{0}' AND ObjType='{1}') ", strUserGUID, strType)
            sbSQL.Append(" BEGIN ")
            sbSQL.AppendFormat(" UPDATE myCurrArgs SET ArgGUID = '{0}' ,LastUpdate = GETDATE() ", strProjGUID)
            sbSQL.AppendFormat(" WHERE ObjType='{0}' AND UserGUID ='{1}' ", strType, strUserGUID)
            sbSQL.Append(" END ")
            sbSQL.Append(" ELSE ")
            sbSQL.Append(" BEGIN ")
            sbSQL.Append(" INSERT INTO myCurrArgs ( UserGUID ,ObjType ,ArgGUID ,LastUpdate ) VALUES (")
            sbSQL.AppendFormat(" '{0}','{1}','{2}',GETDATE() )", strUserGUID, strType, strProjGUID)
            sbSQL.Append(" END ")
        Next

        If MyDB.ExecSQL(sbSQL.ToString()) > 0 Then
            Return True
        End If

        Return False
    End Function

    ''' <summary>
    ''' 设置用户当前公司
    ''' </summary>
    ''' <param name="strBUGUID">公司GUID</param>
    ''' <param name="strBUName">公司名称</param>
    ''' <returns>True or False</returns>
    ''' <remarks></remarks>
    Private Function SetDefaultUnit(ByVal strBUGUID As String, ByVal strBUName As String, ByVal strIsEndCompany As String) As Boolean

        Try
            '保存到Seession
            Session("BUGUID") = strBUGUID
            Session("BUName") = strBUName
            '获取是否末级公司

            If String.Compare(strIsEndCompany, "true", True) = 0 Then
                strIsEndCompany = "1"
            Else
                strIsEndCompany = "0"
            End If

            Session("IsEndCompany") = strIsEndCompany
            Session("MySessionState") = Guid.NewGuid.ToString()

            '保存到Cookie
            Response.Cookies("mycrm_company").Value = strBUGUID
            Response.Cookies("mycrm_company").Expires = Today.AddDays(365)

            Response.Cookies("mycrm_isendcompany").Value = strIsEndCompany
            Response.Cookies("mycrm_isendcompany").Expires = Today.AddDays(365)

            '在临时表中保存当前公司
            Mysoft.Map.Utility.General.InsertKeywordValue2myTemp(Session("UserGUID") & "_" & Session.SessionID, "[当前公司]", Session("BUGUID"))

        Catch ex As Exception
            Return False
        End Try

        Return True
    End Function

End Class


